package movee.io.cluster;

import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import movee.utils.network.RestTemplateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

import static org.springframework.http.HttpMethod.POST;

/**
 *
 *
 * @author movee
 */
@Slf4j
@Service
public class AppClusterClient {

    private static final String PATH = "/v1/app/cluster/event/task/scheduled";

    private final RestTemplate restTemplate;
    private final HttpHeaders headers;

    public AppClusterClient() {

        this.headers = new HttpHeaders();
        this.headers.setContentType(MediaType.APPLICATION_JSON);
        this.headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        this.headers.setCacheControl("no-cache");

        this.restTemplate = RestTemplateUtils.newRestTemplate(10000L, 3000L, 300000L, 200, 100);
    }

    /**
     * 异步通知
     * @param uri 目标host
     */
    public void notifyScheduledTask(String uri) {
        if (StringUtils.isEmpty(uri)) {
            log.error("uri is null or empty");
            return;
        }

        try {
            String url = uri + PATH;
            HttpEntity<String> requestHttpEntity = new HttpEntity<>(headers);
            restTemplate.exchange(url, POST, requestHttpEntity, String.class);
        } catch (RetryableException e) {
            log.error("notifyScheduledTask failed, uri: {}", uri);
        }
    }


}
